var MiTool = {
    ctxPath: "",
    addCtx: function (ctx) {
        if (this.ctxPath == "") {
            this.ctxPath = ctx;
        }
    },
    prompt: function (options, callback) {
        parent.layer.prompt(options, callback);
    },
    close: function (index) {
        parent.layer.close(index);
    },confirm: function (tip, ensure) {//询问框
        parent.layer.confirm(tip, {
            btn: ['确定', '取消']
        }, function (index) {
            parent.layer.close(index);
            ensure();
        }, function (index) {
            parent.layer.close(index);
        });
    },
    log: function (info) {
        console.log(info);
    },
    alert: function (info, iconIndex) {
        parent.layer.msg(info, {
            icon: iconIndex
        });
    },
    info: function (info) {
        MiTool.alert(info, 0);
    },
    success: function (info) {
        MiTool.alert(info, 1);
    },
    error: function (info) {
        MiTool.alert(info, 2);
    },
    infoDetail: function (title, info) {
        var display = "";
        if (typeof info == "string") {
            display = info;
        } else {
            if (info instanceof Array) {
                for (var x in info) {
                    display = display + info[x] + "<br/>";
                }
            } else {
                display = info;
            }
        }
        parent.layer.open({
            title: title,
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: ['950px', '600px'], //宽高
            content: '<div style="padding: 20px;">' + display + '</div>'
        });
    },
    writeObj: function (obj) {
        var description = "";
        for (var i in obj) {
            var property = obj[i];
            description += i + " = " + property + ",";
        }
        layer.alert(description, {
            skin: 'layui-layer-molv',
            closeBtn: 0
        });
    },
    showInputTree: function (inputId, inputTreeContentId, leftOffset, rightOffset) {
        var onBodyDown = function (event) {
            if (!(event.target.id == "menuBtn" || event.target.id == inputTreeContentId || $(event.target).parents("#" + inputTreeContentId).length > 0)) {
                $("#" + inputTreeContentId).fadeOut("fast");
                $("body").unbind("mousedown", onBodyDown);// mousedown当鼠标按下就可以触发，不用弹起
            }
        };

        if(leftOffset == undefined && rightOffset == undefined){
            var inputDiv = $("#" + inputId);
            var inputDivOffset = $("#" + inputId).offset();
            $("#" + inputTreeContentId).css({
                left: inputDivOffset.left + "px",
                top: inputDivOffset.top + inputDiv.outerHeight() + "px"
            }).slideDown("fast");
        }else{
            $("#" + inputTreeContentId).css({
                left: leftOffset + "px",
                top: rightOffset + "px"
            }).slideDown("fast");
        }

        $("body").bind("mousedown", onBodyDown);
    },
    baseAjax: function (url, tip) {
        var ajax = new $ax(Feng.ctxPath + url, function (data) {
            Feng.success(tip + "成功!");
        }, function (data) {
            Feng.error(tip + "失败!" + data.responseJSON.message + "!");
        });
        return ajax;
    },
    changeAjax: function (url) {
        return Feng.baseAjax(url, "修改");
    },
    zTreeCheckedNodes: function (zTreeId) {
        var zTree = $.fn.zTree.getZTreeObj(zTreeId);
        var nodes = zTree.getCheckedNodes();
        var ids = "";
        for (var i = 0, l = nodes.length; i < l; i++) {
            ids += "," + nodes[i].id;
        }
        return ids.substring(1);
    },
    eventParseObject: function (event) {//获取点击事件的源对象
        event = event ? event : window.event;
        var obj = event.srcElement ? event.srcElement : event.target;
        return $(obj);
    },
    sessionTimeoutRegistry: function () {
        $.ajaxSetup({
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            complete: function (XMLHttpRequest, textStatus) {
                //通过XMLHttpRequest取得响应头，sessionstatus，
                var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus");
                if (sessionstatus == "timeout") {
                    //如果超时就处理 ，指定要跳转的页面
                    window.location = Feng.ctxPath + "/global/sessionError";
                }
            }
        });
    },
    initValidator: function(formId,fields){
        $('#' + formId).bootstrapValidator({
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: fields,
            live: 'enabled',
            message: '该字段不能为空'
        });
    },
    file2Base64 : function(event, callback){
        if(event.target.files.length){
            var fileEl = $(event.target);
            var reader = new FileReader();
            if(event.target.files[0].size > 1024 * 1024){
                Feng.alert("图片大小不能超过1M");
                event.target.value = '';
                return false;
            }
            reader.readAsDataURL(event.target.files[0]);
            reader.onload = function(e){
                fileEl.attr('base64', e.target.result);
                if(callback && typeof callback == 'function'){
                    callback(e.target.result);
                }
            };
        }
    },
    mutilFile2Base64 : function(event){
        if(event.target.files.length){
            var fileEl = $(event.target);

            var files = event.target.files;
            if(files.length > 5){
                Feng.alert("最多上传5张图");
                event.target.value = '';
                return false;
            }
            for(var i = 0; i < files.length; i++){
                if(files[i].size > 1024 * 1024){
                    Feng.alert("图片大小不能超过1M");
                    event.target.value = '';
                    return false;
                }
            }
            for(var i = 0; i < 5; i++){
                fileEl.removeAttr('base64' + i);
            }
            for(var i = 0; i < files.length; i++) {
                (function(j){
                    var reader = new FileReader();
                    reader.readAsDataURL(files[i]);
                    reader.onload = function (e) {
                        console.log(j)
                        fileEl.attr('base64' + j, e.target.result);
                    };
                })(i);
            }
        }
    },
    isMobile: function(){
        return (navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i));
    },
    isArray: function(o) {
        return Object.prototype.toString.call(o) === '[object Array]';
    },
    /**
     * 获取日期
     * @param val 日期范围 (now)|(week)|(month)|(start[,end])
     *      now：今日；week：本周；month：本月；
     *      start 起始时间，类型为整数；end 结束时间，类型为整数，默认到当前时间
     *      示例：假设当前日期为2018-09-06，-5：返回[2018-09-01,2018-09-06]，-5,-1：返回[2018-09-01,2018-09-05]
     * @param format 日期格式，默认yyyy-MM-dd
     * @returns {*}
     */
    getDate : function(val, format){
        format = format || 'yyyy-MM-dd';
        var now = new Date();
        var nowStr = now.format(format);
        if(val === 'now'){ // 本日
            return [nowStr,nowStr];
        }else if(val === 'week'){ // 本周
            var day = now.getDay();
            day = day == 0 ? 7 : day;
            now.setDate(now.getDate() - day + 1);
            var firstDayOfWeek = now.format(format);
            return [firstDayOfWeek, nowStr];
        }else if(val === 'month'){ // 本月
            now.setDate(1);
            var firstDayOfMonth = now.format(format);
            return [firstDayOfMonth, nowStr];
        }else if(val && val.match(/^-?\d+/g)){ // 范围，'-7'、'-7,' 或者 '-7,-2'
            var arr = val.split(',');
            now.setDate(now.getDate() + parseInt(arr[0]));
            var start = now.format(format);
            var end = nowStr;
            if(arr[1]){
                now = new Date();
                now.setDate(now.getDate() + parseInt(arr[1]));
                end = now.format(format);
            }
            return [start, end];
        }
        return null;
    },
    loadPie: function(el){
        var jqEl = $(el);
        var url = jqEl.attr('data-url');
        var params = {};
        var paramClass = jqEl.attr('data-param');
        if(paramClass){
            $("." + paramClass).each(function(idx, domEl){
                params[domEl.name] = domEl.value;
            });
        }
        var idx = layer.load(2);
        $.ajax({
            type: "POST",
            url: Feng.ctxPath + url,
            data: params,
            success: function (res) {
                layer.close(idx);
                var _series = [];
                var legend;
                var data = res;
                if(res.ext){
                    data = res.data;
                    for(var key in res.ext){
                        $('#' + key).html(res.ext[key]);
                    }
                }
                if(res.muti){
                    var left = 25;
                    for(var key in res.data){
                        _series.push({
                            name: key,
                            type: 'pie',
                            radius : ['25%', '55%'],
                            center : [left + '%', '50%'],
                            data: res.data[key],
                            label: {
                                formatter: '{a}-{b}\n{c}\n{d}%'
                            }
                        });
                        left += 50;
                    }
                }else{
                    legend = [];
                    for(var i in data){
                        legend.push(data[i].name);
                    }
                    _series.push({
                        name: jqEl.attr('data-name'),
                        type: 'pie',
                        radius : ['25%', '55%'],
                        data: data,
                        label: {
                            formatter: '{b}\n{c}\n{d}%'
                        }
                    });
                }
                echarts.init(jqEl.get(0), 'macarons').setOption({
                    title : {
                        text: jqEl.attr('data-title') || null,
                        subtext: jqEl.attr('data-subtitle') || null
                    },
                    tooltip : {
                        trigger: 'item',
                        formatter: "{a}<br/>{b}: {c} ({d}%)"
                    },
                    legend: {
                        y: 'bottom',
                        data: legend
                    },
                    series : _series
                });
            }, error: function () {
                layer.close(idx);
            }
        });
    },
    /**
     * 加载曲线图，支持单曲线图和多曲线图
     * 单曲线图后台返回数据格式为：{"2018-08-01": 9.8,"2018-08-02": 10.3}
     * 多曲线图后台返回数据格式为：{"x":["2018-08-01","2018-08-02"], "data":{"充值":["2018-08-01":9.8,"2018-08-02": 10.3],"提现":["2018-08-01":11.8]},"ext":{"sum":199}}
     * @param el
     */
    loadLine: function(el){
        var jqEl = $(el);
        var url = jqEl.attr('data-url');
        var params = {};
        var paramClass = jqEl.attr('data-param');
        if(paramClass){
            $("." + paramClass).each(function(idx, domEl){
                params[domEl.name] = domEl.value;
            });
        }
        var idx = layer.load(2);
        $.ajax({
            type: "POST",
            url: Feng.ctxPath + url,
            data: params,
            success: function(res){
                layer.close(idx);
                var xData, yData = [], legendData, tmpArr;
                // x轴数据，用于多条曲线的情况
                if(res.x){
                    xData = res.x;
                    var tmpData;
                    legendData = [];
                    for(var key in res.data){
                        tmpArr = [];
                        tmpData = res.data[key];
                        for(var i in xData){
                            tmpArr.push(tmpData[xData[i]] || 0);
                        }
                        yData.push({
                            name: key,
                            data: tmpArr,
                            type: 'line',
                            areaStyle: jqEl.attr('data-area') ? {} : null,
                            smooth: true
                        });
                        legendData.push(key);
                    }
                    if(res.ext){
                        for(var key in res.ext){
                            $('#' + key).html(res.ext[key]);
                        }
                    }
                }else{
                    tmpArr = [];
                    xData = [];
                    for(var key in res){
                        xData.push(key);
                        tmpArr.push(res[key]);
                    }
                    yData.push({
                        data: tmpArr,
                        type: 'line',
                        areaStyle: jqEl.attr('data-area') ? {} : null,
                        smooth: true
                    });
                }
                echarts.init(jqEl.get(0), 'macarons').setOption({
                    title : {
                        text: jqEl.attr('data-title') || null,
                        subtext: jqEl.attr('data-subtitle') || null
                    },
                    tooltip : {
                        trigger: 'axis'
                    },
                    legend: {
                        data: legendData
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: xData
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: yData
                });
            },error: function () {
                layer.close(idx);
            }
        });
    },
    isJSON: function(str) {
        if (typeof str == 'string') {
            try {
                var obj = JSON.parse(str);
                return typeof obj == 'object' && obj;
            } catch(e) {
                return false;
            }
        }
        return false;
    },
    showFormGroupEl: function(id){
        var el = $('#' + id).parent().parent();
        el.show();
        el.next('.hr-line-dashed').show();
    },
    hideFormGroupEl: function(id){
        var el = $('#' + id).parent().parent();
        el.hide();
        el.next('.hr-line-dashed').hide();
    },
    notEmptyValidators: function (name) {
        return {
            notEmpty: {
                message: name + '不能为空'
            }
        };
    },
    nameValidators: function (name, min, max) {
        return {
            notEmpty: {
                message: name + '不能为空'
            },
            stringLength: {
                min: min || 2,
                max: max || 60,
                message: name + '长度必须在' + (min || 2) + '到' + (max || 60) + '位之间'
            }
        };
    },
    intValidators: function (name, maxLen) {
        return {
            notEmpty: {
                message: name + '不能为空'
            },
            numeric: {
                message: name + '只能必须是整数'
            },
            stringLength: {
                min: 1,
                max: maxLen || 10,
                message: name + '长度必须在1到' + (maxLen || 10) + '位之间'
            }
        };
    },
    decimalValidators: function (name, len) {
        len = len || 8;
        return {
            notEmpty: {
                message: name + '不能为空'
            },
            regexp: {
                regexp: new RegExp('^\\d{1,' + len + '}(\.\\d{1,2})?$'),
                message: name + '必须在0到' + Math.pow(10, len + 1) + '之间且小数点后最多2位'
            }
        };
    },
    disable: function(elId){
        $('#' + elId).attr('disabled', 'disabled');
    },
    enable: function(elId){
        $('#' + elId).removeAttr('disabled');
    },
    linkFmt : function(link){
        return link ? '<a href="'+link+'" target="_blank">查看</a>' : '-';
    },
    imgFmt : function(value){
        return value ? '<a class="view_img" href="javascript:void(0)">查看</a>' : '-';
    },
    imgEvents :  {
        'click .view_img': function (e, value, row, index) {
            Feng.photos(value);
        }
    },
    photos : function(imgUrls){
        if(!Feng.isArray(imgUrls)){
            imgUrls = imgUrls.split('#');
        }
        var imgData = [];
        for(var i in imgUrls){
            imgData.push({
                "pid": i, //图片id
                "src": imgUrls[i] //原图地址
            });
        }
        layer.photos({
            maxHeight : 500,
            photos : {
                "title": "", //相册标题
                "id": 123, //相册id
                "start": 0, //初始显示的图片序号，默认0
                "data": imgData //相册包含的图片，数组格式
            },
            anim : 5
        });
    },
    cutstr: function (str, len) {
        var temp;  // 定义新的字符来存放每次截取的字符
        var icount = 0; // 定义变量来记录已经截取的字符串的长度
        var patrn = /[^\x00-\xff]/; // 正则判断字符是否匹配非单字节的字符（例如汉字、汉字符号，单字节字符包含英文字母、数字、英文符号等。）
        var strre = " ";
        for (var i = 0; i < str.length; i++) {
            if (icount < len) { //看了很多博客写的这里是icount < len - 1, 但是觉得是不对的，应该是icount < len, 如不正确，请指正！
                temp = str.substr(i, 1);
                if (patrn.exec(temp) == null) {
                    icount += 1; //如果是单字节字符，则长度+1；
                } else {
                    icount += 2; //如果是双字节字符，则长度+2；
                }
                strre += temp;
            } else {
                break;
            }
        }
        return strre;
    },
    checkResult: function (result){
        let code = result.code;
        let flag = false
        if (code === 100){
            layer.msg(result.msg, {icon: 1});
        } else if (code === 200){
            return result.data;
        } else if (code === 400){//错误提示
          layer.msg(result.msg, {time: 2000,anim: 4});
        } else if (code == '4001'){//没登录
          localStorage.removeItem('token')
          window.setTimeout("location.href='/auth/login'");
        } else if (code == '4002'){//请求参数有误
          layer.msg("请求参数有误请检查后重试", {time: 2000,anim: 4});
        } else if (code == '4003'){//数据不存在
          layer.msg("数据不存在", {time: 2000,anim: 4});
        } else if (code == '4005'){
          layer.msg("权限异常", {time: 2000, anim: 4});
        } else {
          layer.msg("系统错误，请联系管理员", {time: 2000, anim: 4});
        }
        return flag;
    },
    getPathValue:function (key){
      var  url= window.location.href;
      var  ss = url.split('/');
      for(var i =0 ;i<ss.length;i++){
          if(ss[i]==key){
            return ss[i+1]
          }
      }
      return "";
    },
    addVal:function (el, val){
      $('#'+el).empty();
      $('#'+el).append(val)
    },
    getCookie:function (name) {
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
        if(arr=document.cookie.match(reg)){
            return unescape(arr[2]);
        } else {
            return null;
        }
    },
    isPhone:function(phone) {
        var regMobile = /^1[3-9]\d{9}$/
        return regMobile.test(phone)
    }
};
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.format = function(fmt){
    var o = {
        "M+": this.getMonth()+1,
        "d+": this.getDate(),
        "H+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "S+": this.getMilliseconds()
    };
    fmt = fmt || 'yyyy-MM-dd';
    //因位date.getFullYear()出来的结果是number类型的,所以为了让结果变成字符串型，下面有两种方法：
    if(/(y+)/.test(fmt)){
        //第一种：利用字符串连接符“+”给date.getFullYear()+""，加一个空字符串便可以将number类型转换成字符串。
        fmt=fmt.replace(RegExp.$1,(this.getFullYear()+"").substr(4-RegExp.$1.length));
    }
    for(var k in o){
        if (new RegExp("(" + k +")").test(fmt)){
            //第二种：使用String()类型进行强制数据类型转换String(date.getFullYear())，这种更容易理解。
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(String(o[k]).length)));
        }
    }
    return fmt;
}

